#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   request.py
@Time    :   2023/11/21 15:56:44
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import json

def get_request_ip(request):
    """
    获取请求IP
    :param request:
    :return:
    """
    x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR", "")
    if x_forwarded_for:
        ip = x_forwarded_for.split(",")[-1].strip()
        return ip
    ip = request.META.get("REMOTE_ADDR", "") or getattr(request, "request_ip", None)
    return ip or "unknown"

def get_request_data(request):
    """
    获取请求参数
    :param request: 请求对象
    :return: 请求参数的字典
    """
    request_data = getattr(request, "request_data", None)
    if request_data:
        return request_data
    data: dict = {**request.GET.dict(), **request.POST.dict()}
    if not data:
        try:
            body = request.body
            if body:
                data = json.loads(body)
        except Exception as e:
            pass
        if not isinstance(data, dict):
            data = {"data": data}
    for key, value in data.items():
        if isinstance(value, str) and "password" in key:  
            data[key] = "*" * len(value)
    return data


def get_request_path(request, *args, **kwargs):  
    """  
    获取请求路径，并根据参数进行修改  
    :param request: 请求对象  
    :param args: 额外的路径参数  
    :param kwargs: 其他关键字参数  
    :return: 修改后的请求路径  
    """  
    request_path = getattr(request, "request_path", None)  
    if request_path:  
        return request_path  
    
    # 存储路径值的列表
    path_values = []  
    for arg in args:  
        if len(arg) == 0:  
            continue  
        if isinstance(arg, str):  
            path_values.append(arg)  
        elif isinstance(arg, (tuple, set, list)):  
            path_values.extend(arg)  
        elif isinstance(arg, dict):
            path_values.extend(arg.values())
    if len(path_values) == 0:  
        return request.path  
    path = request.path  
    for value in path_values:
        path = path.replace("/" + value, "/" + "{id}")
    return path